package com.example.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import io.jmnarloch.spring.cloud.ribbon.support.RibbonFilterContextHolder;
import javax.servlet.http.HttpServletRequest;

@Component
public class GrayFilter extends ZuulFilter {
    private static final String GRAY = "gray";
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        //是否开启过滤
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //实现灰度逻辑
        //前端在请求头中携带灰度标识字段
        //服务注册时加入metadata数据，代表该服务节点为灰度节点
        //1.首先从头部中获取标识
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String header = request.getHeader("gray_header");
        //将灰度的请求转发到meataData中forward为1的服务
        if(StringUtils.equals(header,GRAY)){
            RibbonFilterContextHolder.getCurrentContext().add("forward","1");
        }else {
            RibbonFilterContextHolder.getCurrentContext().add("forward","2");
        }
        return null;
    }
}
